/**
 * 
 */
package com.iwords.web.action;

import com.iwords.service.ExamSentencesServiceLocal;
import com.iwords.service.HotSentencesServiceLocal;
import com.iwords.service.IWordsSearchServiceLocal;
import com.iwords.service.WordServiceLocal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;

import com.iwords.utils.StringUtils;

import com.iwords.service.object.ExamSentencesEntity;
import com.iwords.service.object.HotSentencesEntity;
import com.iwords.service.object.SysLibWordsEntity;
import com.iwords.web.base.BaseAction;

/**
 * @author      BOLIN.HBC
 * @time        2011-4-30
 * @description 进行Words的操作-words更新和词句匹配操作
 */
@WebServlet(name = "wordsManager", urlPatterns = {"/wordsManager"})
public class WordsManager extends BaseAction<SysLibWordsEntity> {

    /**
     * 
     */
    @EJB
    WordServiceLocal wordService;
    @EJB
    ExamSentencesServiceLocal examSentencesService;
    @EJB
    HotSentencesServiceLocal hotSentencesService;
    @EJB
    IWordsSearchServiceLocal iWordsSearchService;
    private static final long serialVersionUID = 1L;

    public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        String type = req.getParameter("type");
        if ("edit".equals(type)) {
            req.setAttribute("word", wordService.findWordByWordId(Long.parseLong(req.getParameter("wordid"))));
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/faces/editWord.jsp"); // 定向的页面

            rd.forward(req, res);
        } else if ("pipei".equals(type)) {
            SysLibWordsEntity word = initEntity(req);
            word = wordService.findWordByWordId(word.getWordid());
            req.setAttribute("toPage", req.getParameter(("toPage")));

            // 根据单词获取所有选择了的句子
            List<HotSentencesEntity> hotList = wordService.getHotListByWordId(word.getWordid());

            // 更新这些字句的
            for (HotSentencesEntity hot : hotList) {
                ExamSentencesEntity se = examSentencesService.getSentenceById(hot.getSentenceid());
                hot.setSentences(se.getSentence());
                hot.setParaphrase(se.getParaphrase());
            }
            // 选择这个单词所有的句子
            List<ExamSentencesEntity> allList = iWordsSearchService.searchSentences(word.getWordid(), 0, 100);

            for (ExamSentencesEntity entity : allList) {
                entity.setParaphrase(examSentencesService.getSentenceById(entity.getSentenceid()).getParaphrase());
            }

            // 将sentence赋值
            for (int i = allList.size() - 1; i >= 0; i--) {
                ExamSentencesEntity sen = allList.get(i);

                for (HotSentencesEntity hot : hotList) {

                    if (sen.getSentenceid().equals(hot.getSentenceid())) {
                        new Exception("明明没有地方调用这个功能，为什么会输出错误日志？！！ 2011-10-15 added by mellon");
                        allList.remove(i);
                    }
                }

            }

            req.setAttribute("word", word);
            req.setAttribute("selectList", hotList);
            req.setAttribute("unSelectList", allList);
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/faces/pipeiManager.jsp"); // 定向的页面
            rd.forward(req, res);

        } else if ("update".equals(type)) {
            // 更新单词

            SysLibWordsEntity word = initEntity(req);
            wordService.updateWords(word);
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/faces/wordsManager.jsp"); // 定向的页面
            rd.forward(req, res);
        } else if ("updatepipei".equals(type)) {
            Long wordid = Long.parseLong(req.getParameter("wordid"));

            SysLibWordsEntity word = initEntity(req);
            wordService.updateWords(word);

            // 进行新增
            String selectStr[] = req.getParameterValues("getselect"); // sentenceid
            // 进行删除
            String unSelectStr[] = req.getParameterValues("unselect"); //

            // 把页面上的意思全部更新掉,所有的ID,把这个单词关联的句子全部更新掉
            // 通过Lucene获取的所有单词
            List<ExamSentencesEntity> allList = iWordsSearchService.searchSentences(word.getWordid(), 0, 100);

            for (ExamSentencesEntity hot : allList) {
                ExamSentencesEntity entity = new ExamSentencesEntity();
                entity.setSentenceid(hot.getSentenceid());
                String paraphrase = req.getParameter(hot.getSentenceid() + "");
                entity.setParaphrase(paraphrase);
                if (paraphrase != null && paraphrase.length() > 0 && !"null".equals(paraphrase)) {
                    examSentencesService.updateSentence(entity);
                }
            }

            // 插入所有的匹配的句子
            if (selectStr != null && selectStr.length > 0) {
                for (String sele : selectStr) {
                    HotSentencesEntity hot = new HotSentencesEntity();
                    hot.setWordid(wordid);
                    hot.setSentenceid(Long.parseLong(sele));
                    hot.setRank(0L);
                    hotSentencesService.insertHost(hot);

                }
            }
            // 删除所有不要的句子
            if (unSelectStr != null && unSelectStr.length > 0) {
                for (String sele : unSelectStr) {
                    HotSentencesEntity hot = new HotSentencesEntity();
                    hot.setWordid(wordid);
                    hot.setSentenceid(Long.parseLong(sele));
                    hotSentencesService.deleteHost(hot);

                }

            }

            int page = Integer.parseInt(req.getParameter("toPage") == null ? "0" : req.getParameter("toPage"));
            Map<String, Object> map = wordService.getNextWord(word.getWordid(), page, false);
            if ("true".equals(map.get("page").toString())) {
                page = page + 1;
            }
            res.sendRedirect("wordsManager?toPage=" + page + "&type=pipei&wordid=" + (map.get("id") == null ? "" : map.get("id")));
        } else if ("translation".equals(type)) {

            String ids[] = req.getParameterValues("sentenceids");
            List<ExamSentencesEntity> entitys = new ArrayList<ExamSentencesEntity>();

            if (ids != null && ids.length > 0) {

                for (int i = 0; i < ids.length; i++) {

                    String p = req.getParameter(ids[i]);
                    if (p != null && p.trim().length() > 0 && !"null".equals(p)) {
                        ExamSentencesEntity entity = new ExamSentencesEntity();
                        entity.setSentenceid(Long.parseLong(ids[i]));
                        entity.setParaphrase(p);
                        entitys.add(entity);
                    }

                }

            }

            examSentencesService.updateSentences(entitys);

            int page = (req.getParameter("toPage") == null ? 0 : Integer.parseInt(req.getParameter("toPage")));

            List<Long> hotList = hotSentencesService.getAllHotSentences(page);

            List<ExamSentencesEntity> sentenceList = new ArrayList<ExamSentencesEntity>();

            StringBuilder strs = new StringBuilder();

            for (Long hot : hotList) {
                strs.append(hot).append(",");
            }

            if (strs.length() > 0) {
                sentenceList = examSentencesService.getSentenceList(strs.substring(0, strs.length() - 1));
            }

            req.setAttribute("count", hotSentencesService.getHotCount() + "");
            req.setAttribute("toPage", page + "");
            req.setAttribute("sentenceList", sentenceList);

            RequestDispatcher rd = getServletContext().getRequestDispatcher("/faces/translation.jsp"); // 定向的页面

            rd.forward(req, res);


        } else {
            // 根据首字母去查询所有的单词

            int page = Integer.parseInt(req.getParameter("toPage") == null ? "0" : req.getParameter("toPage"));

            List<SysLibWordsEntity> words = wordService.getAllManagerWords("", page);

            req.setAttribute("toPage", page + "");
            req.setAttribute("count", wordService.getAllManagerWordsCount() + "");
            // 获取每一个单词现在匹配了多少次
            for (SysLibWordsEntity word : words) {
                word.setNum(hotSentencesService.getHotListByWordId(word.getWordid()).size());
            }

            req.setAttribute("words", words);

            RequestDispatcher rd = getServletContext().getRequestDispatcher("/faces/wordsManager.jsp"); // 定向的页面

            rd.forward(req, res);
        }
    }

    public SysLibWordsEntity initEntity(HttpServletRequest req) {

        SysLibWordsEntity entity = new SysLibWordsEntity();
        String wordid = req.getParameter("wordid");
        if (StringUtils.isNotBlank(wordid)) {
            entity.setWordid(Long.parseLong(req.getParameter("wordid")));
        }
        String libid = req.getParameter("libid");
        if (StringUtils.isNotBlank(libid)) {
            entity.setLibid(Long.parseLong(req.getParameter("libid")));
        }
        String spelling = req.getParameter("spelling");
        entity.setSpelling(spelling);
        String meaning = req.getParameter("meaning");
        entity.setMeaning(meaning);
        String phonetics = req.getParameter("phonetics");
        entity.setPhonetics(phonetics);

        return entity;
    }
}
